package dbcp.shia.util;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {

    private static final String CONFIG_FILE = "config.properties";

    private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionUtil.class);

    private static DataSource dataSource;

    private static Properties properties;

    static {
        try {
            InputStream inputStream = new BufferedInputStream(ConnectionUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE));
            properties = new Properties();
            properties.load(inputStream);

        } catch (FileNotFoundException e) {
            LOGGER.error("get config properties exception:", e);
        } catch (IOException e) {
            LOGGER.error("get config properties exception:", e);
        }
    }

    static {
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            LOGGER.error("create dataSource exception:", e);
        }
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            LOGGER.error("get connection exception:", e);
        }

        return connection;
    }

    public static void freeResources(PreparedStatement preparedStatement, Connection connection) {
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch(SQLException e) {
            LOGGER.error("free db resources exception:", e);
        }
    }
}
